<template>
    <div id="storeEdit">
        <el-dialog
                :title='$t("common.orderEdit")'
                :visible.sync="dialogVisible"
                :before-close="cancel"
                width="30%">
            <div>
                <el-form ref="form" :model="form" :rules="rules" label-width="80px" label-position="left"
                         :hide-required-asterisk="false">
                    <el-form-item v-if="key!=='id' && !(key === 'add' && !form.id)" v-for="item,key in form"
                                  :label="$t('store.'+key)" :prop="key">
                        <el-select v-if="key==='productId'" v-model="form[key]" :clearable="true"
                                   :disabled="formDisabled(key)"
                                   filterable
                                   remote
                                   :remote-method="remoteMethod"
                                   @clear="clearMethod"
                                   :placeholder="$t('common.selectPlaceholderTip')">
                            <el-option
                                    v-for="item in productOptions"
                                    @click.native="changeAttr(item)"
                                    :key="item.value"
                                    :label="item.value+' | '+item.label"
                                    :value="item.value">
                            </el-option>
                        </el-select>
                        <el-select v-else-if="key==='warehouseId'" v-model="form[key]" :clearable="true"
                                   :disabled="formDisabled(key)"
                                   :placeholder="$t('common.selectPlaceholderTip')">
                            <el-option
                                    v-for="item in warehouseOptions"
                                    :key="item.value"
                                    :label="$t('option.'+item.label).indexOf('.')>-1?item.label:$t('option.'+item.label)"
                                    :value="item.value">
                            </el-option>
                        </el-select>
                        <div  v-else-if="key==='property'">
                            <div v-if="productAttr" v-for="attr,attrKey in productAttr" class="attrGroup">
                                <div class="attrName">{{attrKey}}</div>
                                <el-radio-group v-model="productSelectAttr[attrKey]"
                                                :disabled="formDisabled(key)"
                                                class="attrValueGroup">
                                    <el-radio
                                            v-for="value in attr"
                                            :label='value'
                                            @click.native.prevent="changeSelectAttr(attrKey,value)">{{value}}
                                    </el-radio>
                                </el-radio-group>
                            </div>
                        </div>
                        <el-input-number v-else v-model="form[key]"
                                         :controls='false'
                                         :disabled="formDisabled(key)"
                                         :min="inputMinNumber[key]">
                        </el-input-number>

                    </el-form-item>
                </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
            <el-button @click="cancel">{{$t('common.cancel')}}</el-button>
            <el-button type="primary" @click="confirm">{{$t('common.confirm')}}</el-button>
            </span>
        </el-dialog>

    </div>
</template>

<script>
    import {mapState} from 'vuex'
    export default {
        name: "storeEdit",
        props: {
            data: {
                type: Object,
                default() {
                    return {}
                }
            },
            changeRow: {
                type: Object,
                default() {
                    return {}
                }
            },
            refresh: {
                type: Boolean,
                default: false
            }
        },
        data() {
            let property = (rule, value, callback) => {
                if(JSON.stringify(this.productAttr) === '{}'){
                    callback();
                }else{
                    for (let key of Object.keys(this.productAttr)) {
                        if(!this.productSelectAttr[key]){
                            callback(new Error(this.$t('common.productIdAttrValidTip')));
                        }
                    }
                }
            };
            let storageCounts = (rule, value, callback) => {
                if(value > 0 ){
                    callback();
                }else{
                    callback(new Error(this.$t('common.storageCountsValidTip')));
                }
            };
            return {
                dialogVisible: false,
                productSelectAttr: {},
                productAttr: {},
                productOptions: [],
                form: {
                    id: '',
                    productId: '',
                    property: '',
                    warehouseId: '',
                    // purchase:'',
                    storageCounts: '',
                    add: '',
                    // shipCounts:''
                },
                rules: {
                    storageCounts: [{required: true, message: this.$t('common.storageCountsValidTip'), trigger: 'blur'},
                        {validator: storageCounts, trigger: 'blur'}],
                    productId: [{required: true, message: this.$t('common.productIdValidTip'), trigger: 'blur'}],
                    warehouseId: [{required: true, message: this.$t('common.warehouseIdValidTip'), trigger: 'blur'}],
                    add: [{required: true, message: this.$t('common.storageCountsValidTip'), trigger: 'blur'}],
                    property:[{validator: property, trigger: 'blur'}],
                },
                inputMinNumber: {
                    purchase: 1,
                    storageCounts: 1,
                    shipCounts: 0,
                    add: -10000,
                },

            }
        },
        methods: {
            changeVisiable() {
                this.dialogVisible = !this.dialogVisible
            },
            formDisabled(key,childKey) {
                let disable = false
                let list = ['property', 'warehouseId', 'productId', 'storageCounts']
                this.form.id && (disable = list.includes(key))
                if(childKey === 'property'){
                    if(JSON.stringify(this.productAttr) === '{}'){
                        disable = true
                    }
                }
                return disable
            },
            initData() {
                for (let key of Object.keys(this.form)) {
                    this.form[key] = this.data[key]||''
                    if (key === 'property' && this.form[key]) {
                        let attr = JSON.parse(this.form[key])
                        for (let i in  attr) {
                            this.changeSelectAttr(i, attr[i],true)
                        }
                    }
                }
                if (this.form.id) {
                    this.remoteMethod(this.form.productId,true)
                }else{
                    this.changeAttr()
                }
            },
            remoteMethod(id,attr){
                let params = {
                    pageSize: 1,
                    currentPage: 1,
                    id: id
                }
                this.$productList(params).then(response=>{
                    this.productOptions=[]
                    if(response.data){
                        response.data.forEach((v)=>{
                            let option = {
                                value:v.productId,
                                label:v.productName,
                                productAttr:v.productAttr,
                            }
                            this.productOptions.push(option)
                        })
                       if(attr)  this.changeAttr(this.productOptions[0],true)
                    }else{
                        this.changeAttr('')
                    }
                })
            },
            clearMethod(){
              this. changeAttr('')
            },
            changeAttr(v,init) {
                if (!v ||!v.productAttr) {
                    this.productAttr = {}
                    this.productSelectAttr = Object.assign({},{})
                    return
                }
                this.productAttr = JSON.parse(v.productAttr)
                if(!init){
                    this.productSelectAttr = Object.assign({},{})
                }
            },
            changeSelectAttr(k, v,init) {
                if(!init&&this.formDisabled('property')){
                    return
                }
                this.$set(this.productSelectAttr, k, v)
            },
            cancel() {
                this.dialogVisible = false;
                this.$refs.form.clearValidate()
                this.$refs.form.resetFields()
                this.data = {}
            },
            confirm() {
                if (!this.beforeConfirmCheck()) {
                    return false
                }
                let params = JSON.parse(JSON.stringify(this.form)),
                    storageCounts = this.form.add ? this.form.add + params.storageCounts : params.storageCounts,
                    id = this.form.id
                params.storageCounts =  this.form.add?this.form.add:params.storageCounts
                delete params.add
                this.$storeAdd([params]).then(response => {
                    if (response && response.code === 'success') {
                        this.$message.success(this.$t('common.success'))
                        let changeRow = {_Id: 'id'}
                        for (let key of Object.keys(params)) {
                            changeRow[key] = params[key]
                        }
                        changeRow.storageCounts = storageCounts
                        if(id){
                            this.$emit("update:changeRow", changeRow)
                        }else {
                            this.$emit("update:refresh", true)
                        }
                    } else {
                        this.$message.error(this.$t('common.error'))
                    }
                })
                this.cancel()
            },
            beforeConfirmCheck() {
                let valid = true;
                let required = ['warehouseId','productId']
                this.$refs.form.validate((v) => {
                    valid = v
                })
                required.forEach(v=>{
                    if(!this.form[v]){
                        valid = false
                    }
                })
                return valid
            }
        },
        watch: {
            dialogVisible(newV, oldV) {
                if (newV) {
                    this.initData()
                }
            },
            productSelectAttr: {
                handler(newV, oldV) {
                    this.form.property = JSON.stringify(newV)
                },
                deep: true
            }
        },
        computed:{
            ...mapState(['warehouseOptions'])
        }
    }
</script>

<style>
    .attrName {
        color: #555;
        font-weight: 500;
        font-size: 16px;
        line-height: 42px;
        background-color: #d1d1d1;
        text-indent: 2%;
        margin-bottom: 5px;
    }

    .attrValueGroup {
        font-weight: 500;
        font-size: 16px;
        line-height: 30px;
        padding: 5px 20px;
    }

    .attrName:before {
        display: inline-block;
        width: 4px;
        height: 25px;
        background: #c50a1d;
        margin-right: 8px;
        vertical-align: middle;
        content: '';
    }

    .attrGroup {
        padding-bottom: 5px;
        border: 1px dashed #aaa;
        border-top-width: 0;
    }

    #storeEdit .el-input-number--mini {
        min-width: 200px;
    }

    #storeEdit .el-input-number .el-input__inner {
        text-align: left;
    }
</style>